// 引入接口文件
import { getDetail, getArea, shareImg, deleteCode, downloadQrcode, regionArea, getProduct } from './codeChannelServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import { makeAddress, download } from "utils/util"
import { object } from 'prop-types'
// 初始默认状态
const defultState = {
        currentImg: '',
        xxx: '1',
        // loading: false,
        btnLoading: false,
        currentItem: '',
        qrcodeCount: '',
        area1: [],
        products: [],
        biz: {},
        shareModal: false,
        jumpUrl: ''
    }
    // 复制
function copyToClipboard(txt) {
    let input = document.querySelector('#copy_ele')
    if (!input) {
        input = document.createElement('input');
        input.id = 'copy_ele';
        document.getElementById('gug').appendChild(input);
    }
    input.value = txt;
    input.style.opacity = 0;
    try {
        input.select(); // 选择对象
        document.execCommand("Copy");
        message.success('复制成功，链接复制到剪切板中！')
    } catch (error) {
        message.error('复制失败，请刷新页面重试！')
    }
}
// 声明module
const tmpModule = {

    state: cloneDeep(defultState),
    // 入口函数(先执行)
    subscriptions: {
        setup({ dispatch, history }) {
            history.listen(({ pathname, query }) => {
                    console.log(cloneDeep(defultState))
                        // 页面路由匹配时执行
                    if ('' + tmpModule.pathname === '' + pathname) {
                        // 执行业务操作
                        // dispatch({ type: 'getArea', payload:{}});
                        dispatch({ type: 'regionArea', payload: {} });
                        dispatch({ type: 'updateStore', payload: cloneDeep(defultState) });

                    } // end if
                }) // end listen
        },
    },

    // 方法列表
    effects: {
        // *getArea({ payload }, { put, call, select }){
        //   let {biz,products} = yield select(state => state[tmpModule.namespace])
        //   const { data, success } = yield call(getArea);
        //   if(success) {
        //     if(biz.queryForm && biz.queryForm.regionId){
        //       data.map((item,index)=>{
        //         if(biz.queryForm && biz.queryForm.regionId && biz.queryForm.regionId==item.value)
        //         {   
        //             products=item.products
        //         }
        //       })
        //     }
        //     yield put({ type: 'updateStore',payload:{area1:data,products}})
        //   }
        // },
        * regionArea({ payload }, { put, call, select }) {
            let { biz, areaList } = yield select(state => state[tmpModule.namespace])
            const { data, success } = yield call(regionArea);
            if (success) {
                if (biz.queryForm && biz.queryForm.regionId) {
                    data.map((item, index) => {
                        if (biz.queryForm && biz.queryForm.regionId && biz.queryForm.regionId == item.value) {
                            areaList = item.children
                        }
                    })
                }
                yield put({ type: 'updateStore', payload: { area1: data, areaList } })
            }
        },
        * getProduct({ payload }, { put, call, select }) {
            let { biz, products } = yield select(state => state[tmpModule.namespace])
            const { data, success } = yield call(getProduct, payload);
            if (success) {
                products = data
                yield put({ type: 'updateStore', payload: { products } })
            }
        },
        // // 查询记录
        // *getAreaList({ payload }, { put, call, select }){
        //   const { data, success } = yield call(queryAllAddress);
        //   if(success) {
        //       let areaList = []
        //       let arr = [data[0]]
        //       let attr = [data[data.length-1]]
        //       data[0] = {
        //         label:"北京",
        //         value:"110100",
        //         children:arr
        //       }
        //       data[data.length-1]={
        //         label:"澳门",
        //         value:"820000",
        //         children:attr
        //       }
        //       //去掉第三级，
        //       areaList = makeAddress(data,2)
        //     yield put({ type: 'updateStore',payload:{areaList}})
        //   }
        // },
        //获取二维码
        * shareImg({ payload }, { put, call, select }) {
            try {
                yield put({ type: 'updateStore', payload: { loading: true } })
                const { data, success } = yield call(shareImg, payload);
                if (success) {
                    console.log(data)
                    yield put({ type: 'updateStore', payload: { currentImg: data.fileUrl, loading: false, qrcodeCount: data.qrcodeCount } })
                }
            } catch (e) {

            }
        },
        //删除二维码
        * deleteCode({ payload }, { put, call, select }) {
            try {
                const { data, success } = yield call(deleteCode, payload);
                let defultState = yield select(state => state[tmpModule.namespace])
                if (success) {
                    message.success('删除成功', () => {
                        defultState.biz.refreshListDatas(true)
                    })
                } else {

                }
            } catch (e) {}
        },
        //二维码次数计算
        * count({ payload }, { put, call, select }) {
            try {
                let { currentItem, biz } = yield select(state => state[tmpModule.namespace])
                const { data, success } = yield call(downloadQrcode, { id: currentItem.id });
                if (success) {
                    download(data.imgUrl)
                    biz.refreshListDatas(true)
                    yield put({
                        type: 'updateStore',
                        payload: { shareModal: false }
                    })
                }
            } catch (e) {

            }
        },
        //获取活动详细信息(获取跳转地址)
        * getDetail({ payload }, { put, call, select }) {

            let { data, success } = yield call(getDetail, payload);
            if (success) {
                //回来的数据回显
                if (data instanceof Object && JSON.stringify(data) != '{}') {
                    let jumpUrl = data.data.jumpUrl
                    let jumpLocation = data.data.jumpLocation
                    let url = `${jumpUrl}?scene=${payload.id}&sceneType=WeChat`;
                    if (jumpLocation == 3) {
                        if (jumpUrl.indexOf('http') > -1 || jumpUrl.indexOf('https') > -1) {
                            url = `pages/biz/outsizeLink/outsizeLink?scene=${payload.id}&sceneType=WeChat`;
                        }
                    }
                    copyToClipboard(url)
                }
            }

        },
    },
    // 存入状态机
    reducers: {
        updateStore(preState, action) {
            console.log(preState)
            return Object.assign({}, preState, action.payload)
        },
    }
}

export default tmpModule